package com.schoolcloud.share.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.share.entity.Categories;
import com.schoolcloud.share.query.CategoriesQuery;
import com.schoolcloud.share.service.CategoriesService;
import com.schoolcloud.share.mapper.CategoriesMapper;
import com.schoolcloud.share.vo.CategoryTreeVO;
import com.schoolcolud.daomybatisplus.dto.MpPageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hongmizfb
 * @description 针对表【categories(视频内容分类体系)】的数据库操作Service实现
 * @createDate 2025-05-16 18:35:15
 */
@Service
public class CategoriesServiceImpl extends ServiceImpl<CategoriesMapper, Categories>
        implements CategoriesService {

    @Override
    public PageDTO<Categories> getCategoryPage(CategoriesQuery query) {
        Integer parentId = query.getParentId();
        String name = query.getName();
        Integer level = query.getLevel();
        Page<Categories> page = lambdaQuery().eq(parentId != null, Categories::getParentId, parentId)
                .eq(level != null, Categories::getLevel, level)
                .like(name != null, Categories::getName, name).page(query.toMpPage());
        return MpPageUtil.of(page, Categories.class);
    }

    @Override
    public List<CategoryTreeVO> getParentsTree() {
        List<Categories> list = Optional.ofNullable(list()).orElse(Collections.emptyList());
        List<CategoryTreeVO> allNodes = list.stream()
                .map(item -> {
                    CategoryTreeVO vo = new CategoryTreeVO();
                    BeanUtils.copyProperties(item, vo);  // 注意：建议使用更安全的拷贝方式
                    return vo;
                })
                .collect(Collectors.toList());
        // 筛选顶级节点（假设parentId为0或null都是顶级）
        List<CategoryTreeVO> topNodes = allNodes.stream()
                .filter(item -> item.getParentId() == null || item.getParentId() == 0)
                .collect(Collectors.toList());
        CategoryTreeVO categoryTreeVO = new CategoryTreeVO();
        categoryTreeVO.setCategoryId(0);
        categoryTreeVO.setName("顶级分类");
        categoryTreeVO.setChildren(buildTree(topNodes, allNodes));
        ArrayList<CategoryTreeVO> objects = new ArrayList<>();
        objects.add(categoryTreeVO);
        return objects;
    }

    @Override
    public List<CategoryTreeVO> getTreeList() {
        List<Categories> list = lambdaQuery().list();
        List<CategoryTreeVO> allList = list.stream().map(item -> {
            CategoryTreeVO vo = new CategoryTreeVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).toList();
        List<CategoryTreeVO> collect = allList.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        return buildTree(collect, allList);
    }

    /**
     * 构建树形结构
     *
     * @param parentNodes 父节点列表
     * @param allNodes    所有节点列表
     * @return 构建好的树形结构
     */
    private List<CategoryTreeVO> buildTree(List<CategoryTreeVO> parentNodes, List<CategoryTreeVO> allNodes) {
        if (parentNodes == null || parentNodes.isEmpty()) {
            return Collections.emptyList();
        }
        parentNodes.forEach(parent -> {
            // 查找当前父节点的直接子节点
            List<CategoryTreeVO> children = allNodes.stream()
                    .filter(child -> Objects.equals(child.getParentId(), parent.getCategoryId()))
                    .collect(Collectors.toList());
            // 递归设置子节点的子节点
            buildTree(children, allNodes);
            // 设置子节点
            parent.setChildren(children);
        });
        return parentNodes;
    }
}




